package org.xs.web.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;

 
public class DateFormat {
	private static final Logger logger= Logger.getLogger(DateFormat.class);
	
    public static final String DATETIME ="yyyy-MM-dd HH:mm:ss";
    public static final String DATETIME_INGORE_S="yyyy-MM-dd HH:mm";
    public static final String DATEONLY ="yyyy-MM-dd";
    public static final String DATE="yyyy-MM-dd";
    public static final SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z",Locale.ENGLISH);
    
	public static Date formatAndWrap(String dateString){
		if(dateString == null || dateString.equals("")) return null;
		SimpleDateFormat format= null;
		if(dateString.lastIndexOf(":") > 0){
			 format = new SimpleDateFormat(DATETIME);
		}else{
			format =new SimpleDateFormat(DATE);
		}
		try {
			return format.parse(dateString);
		} catch (ParseException e) {
			logger.debug("Data format not compolete!,so return null to client");
			return null;
		}
		
	}
	public static String toDateString(Date date){
		if(date == null){
			return null;
		}
		SimpleDateFormat format = new SimpleDateFormat(DATETIME_INGORE_S);
		return format.format(date);
	}
	
	public static Date today(){
		Calendar ca = Calendar.getInstance();
		ca.setTime(new Date());
		ca.set(Calendar.HOUR_OF_DAY, 0);
		return ca.getTime();
	}
	
	public static String dateFormat(Date date,String... format){

		if(date == null){
			return null;
		}
		String useFormat = (format == null || format.length < 1) ? DATETIME : format[0];
		SimpleDateFormat simple = new SimpleDateFormat(useFormat);
		return simple.format(date);
	}
	
	public static Date formatAndWrap(String date,String format){
		SimpleDateFormat df = new SimpleDateFormat(format);
		try {
			return df.parse(date);
		} catch (ParseException e) {
			return null;
		}
	}
	
	
	public static Date toDateAndIngoreS(String dateString){	
		try {
			if(dateString == null){
				return null;
			}
			SimpleDateFormat format = new SimpleDateFormat(DATETIME_INGORE_S);
			return format.parse(dateString);
		} catch (ParseException e) {
			return null;
		}
	}
	
	public static Date convertLongToDate(long dateAsLong){
		 
			Calendar c = Calendar.getInstance();
			c.setTimeInMillis(dateAsLong);
			return c.getTime();
		 
	}
	
	public static String toDateOnlyString(Date date){
		return dateFormat(date,DATEONLY);
	}
	
	public static Date toDate(String dateAsString){
		try {
			if(dateAsString == null){
				return null;
			}
			SimpleDateFormat format = new SimpleDateFormat(DATEONLY);
			return format.parse(dateAsString);
		} catch (ParseException e) {
			return null;
		}
	}
	public static Date toDateAndWrap(String dateAsString,Date dflt){
		try {
			if(dateAsString == null){
				return dflt;
			}
			SimpleDateFormat format = new SimpleDateFormat(DATEONLY);
			return format.parse(dateAsString);
		} catch (ParseException e) {
			return dflt;
		}
	}
	
	public static long convertDateToLong(Object date){
		
		Calendar c = Calendar.getInstance();
		c.setTime((Date)date);
		
		return c.getTimeInMillis();
	}
	
	
	public static String toDateTimeString(String strAsLongDate){
		Date date = convertLongToDate(Long.valueOf(strAsLongDate));
		return dateFormat(date, DateFormat.DATETIME_INGORE_S);
	}
	
	public static String toDateString(Date date ,String split){
		Calendar calendar = Calendar.getInstance(TimeZone.getDefault(), Locale.CHINESE);
		calendar.setTime(date);
		int y = calendar.get(Calendar.YEAR);
		int m = calendar.get(Calendar.MONTH) + 1;
		int d = calendar.get(Calendar.DATE);
		
		return StringUtils.join(new Object[]{y,m,d},split);
	}
	
	public static String toDateString(long dateAsLong){
		return DateFormat.toDateOnlyString(convertLongToDate(dateAsLong));
	}
	
	public static String toDateStringAsLongString(String dateAsLongString){
		return toDateString(Long.valueOf(dateAsLongString));
	}
	
	public static String toDMYString(Date date,String splitDate,String splitTime){
		String dateStr = StringUtils.join(new Object[]{"MM","dd","yyyy"},splitDate);
		String timeStr =StringUtils.join(new Object[]{"HH","mm"},splitTime);
		String datetime= StringUtils.join(new Object[]{dateStr,timeStr},' ');
		return new SimpleDateFormat(datetime).format(date);
	}
	
	public static String toTimeOnlyString(Date date,String split){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int h = calendar.get(Calendar.HOUR);
		int m = calendar.get(Calendar.MINUTE);
		return StringUtils.join(new Object[]{h,m},split);
	}
	
	
	/**
	 * 取本月前的N月
	 */
	public static Date[] getMonthN(int n){
		Calendar to = Calendar.getInstance();
		to.setTime(new Date());
		to.set(Calendar.DAY_OF_MONTH,1);
		int m = to.get(Calendar.MONTH);
		to.set(Calendar.MONTH,  m- n > 0 ? m-n : 0 );
		Date from_ = to.getTime();
		return new Date[]{from_,new Date()};
	}
	
	
	
	
	/********************************************************/
	/**
	 * 本月-开始日至今日
	 * @return month start day and end day
	 */
	public static Date[] monthLimit(Date startDate){
		Calendar from = Calendar.getInstance();
    	from.setTime(startDate);
    	from.set(Calendar.DAY_OF_MONTH, 1);
    	from.set(Calendar.HOUR_OF_DAY, 0);
    	return new Date[]{from.getTime(),startDate};
	}
	/**
	 * 取本月,从开始日期到本月结束
	 * @param startDate
	 * @return
	 */
	public static Date[] monthDays(Date startDate){
		Calendar from = Calendar.getInstance();
    	from.setTime(startDate);
    	from.set(Calendar.DAY_OF_MONTH, 1);
    	from.set(Calendar.HOUR_OF_DAY, 0);
    	Date[] res = new Date[2];
    	res[0] = from.getTime();
    	if(is31Day(from.get(Calendar.MONTH))){
    		from.set(Calendar.DAY_OF_MONTH,31);
    	}else{
    		from.set(Calendar.DAY_OF_MONTH,30);
    	} 
    	res[1] = from.getTime();
    	return res;
	}
	
	public static boolean is31Day(int month){
		month++;
		int[] old = {1,3,5,7,8,10,12};
		for(int i : old){
			if(i == month){
				return true;
			}
		}
		
		return false;
	}
	
	
	/**
	 * 取本周
	 * @param startDate
	 * @return wkke start day and end day
	 */
    public static Date[] weekLimit(Date startDate){
    	Calendar to = Calendar.getInstance();
    	to.setTime(startDate);
    	Date from =startDate;
    	int day = to.get(Calendar.DAY_OF_WEEK);
    	switch(day){
    	case Calendar.MONDAY	: 	from = DateUtils.addDays(from, -0);
    			break;
    	case Calendar.TUESDAY	: 	from = DateUtils.addDays(from, -1);
    			break;
    	case Calendar.WEDNESDAY : 	from = DateUtils.addDays(from, -2);
    			break;
    	case Calendar.THURSDAY 	: 	from = DateUtils.addDays(from, -3);
    			break;
    	case Calendar.FRIDAY 	: 	from = DateUtils.addDays(from, -4);
    			break;
    	case Calendar.SATURDAY 	: 	from= DateUtils.addDays(from, -5);
    			break;
    	case Calendar.SUNDAY 	: 	from = DateUtils.addDays(from, -6);
    	}
    	Calendar fromCalendar = Calendar.getInstance();
    	fromCalendar.setTime(from);
    	fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
    	return new Date[]{fromCalendar.getTime(),to.getTime()};
    }
     /**
      * 取上周
      * @param offset
      * @return week start day and end day
      */ 
    public static Date[] afterWeek(int offset){
    	Calendar from = Calendar.getInstance(); 
    	from.set(Calendar.WEEK_OF_YEAR, from.get(Calendar.WEEK_OF_YEAR)-offset);
    	from.set(Calendar.DAY_OF_WEEK, 1);
    	from.set(Calendar.HOUR_OF_DAY, 0);
		Calendar to = Calendar.getInstance();
		to.set(Calendar.WEEK_OF_YEAR, to.get(Calendar.WEEK_OF_YEAR)-offset);
		to.set(Calendar.DAY_OF_WEEK, 7);
		to.set(Calendar.HOUR_OF_DAY, 0);
		return new Date[]{from.getTime(),to.getTime()};
    }
    /**
     * 获取间隔时间
     * @param date 现在时间
     * @param dateAsLong  以前时间
     * @return	0年0月0日0时0分
     */
   public static String dateTimeByChinese(Date date,long dateAsLong){
	  long offset = date.getTime() - dateAsLong;
	  int year = 0;
	  if(offset > 0){
		  Calendar c1= Calendar.getInstance();
		  c1.setTime(date);
		  Calendar c2= Calendar.getInstance();
		  c2.setTimeInMillis(dateAsLong);  
		  year=  c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
	  } 
	 
	   long yearDie = offset%(1000*60*60*24*365);
	   
	   long day = yearDie / (1000*60*60*24);
	   long dayDie = yearDie % (1000*60*60*24);
	  
	   long hours = dayDie/(1000*60*60);
	   long hoursDie = dayDie % (1000*60*60);
	   
	   long min = hoursDie/(1000*60);
	  
	  StringBuffer buffer = new StringBuffer();
	  if(year > 0){
		  buffer.append(year).append("年");
	  }
	  
	  buffer.append(day).append("天").append(hours).append("时").append(min).append("分");
	  return buffer.toString();
   }
    
    
  
   public static String toGMTString(Date date){
		df.setTimeZone(TimeZone.getTimeZone("GMT"));
		return df.format(date); 
   }
   
   public static Date toGMTDate(String gmt){
	   df.setTimeZone(TimeZone.getTimeZone("GMT"));
	   try {
		return df.parse(gmt);
	} catch (ParseException e) {
		 
	}
	return null;
   }
    
   public static Date dateRange(int minute){
	   Calendar ca = Calendar.getInstance();
	   ca.setTime(new Date());
	   ca.set(Calendar.MINUTE, ca.get(Calendar.MINUTE) + minute);
	   return ca.getTime();
   }
   
}
